var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
// 上传模块
const multer = require('multer');
const upload = multer({
	dest: path.join(__dirname, '../../public/file/essay'),
});
// sql
const query = require('../mysql');

// 获取
router.get('/', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	let inputQuery = req.query.queryInfo.query;
	// let searchType = req.query.queryInfo.searchType;
	let searchType = req.query.searchType;
	let username = req.query.username;
	// 分页效果
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select * from essay where author like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${username}%`]);
	} else {
		let sqlStr = `select * from essay where ${searchType} like ? and author like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`, `%${username}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from essay`;
	let result1 = await query(sqlStr1);

	// 搜索功能

	res.send({ status: 200, result, total: result1[0]['count(*)'] });
});

let essayAddForm;

// 添加
router.post('/', async (req, res) => {
	essayAddForm = req.body.essayAddForm;
	// console.log(req.body);
	let sqlStr = `select * from essay where no=?`;
	let result = await query(sqlStr, [essayAddForm.no]);
	if (result.length != 0) {
		return res.send({ status: 401, message: '论文编号重复' });
	}
	res.send({ status: 100, message: '创建论文信息成功' });
});

router.post('/upload', upload.single('file'), async (req, res, next) => {
	file = req.file;
	saveWord(file, req, res);
});

async function saveWord(file, req, res) {
	let {
		name,
		no,
		keyword,
		author,
		author_unit,
		publisher,
		publish_scope,
		publish_time,
		subject_classification,
		category,
		abstract,
		status,
		remarks,
	} = essayAddForm;
	// console.log(essayAddForm);
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/essay/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `insert into essay(name,no,keyword,author,author_unit,publisher,publish_scope,publish_time,subject_classification,category,abstract,status,essayfile,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;
	let result = await query(sqlStr, [
		name,
		no,
		keyword,
		author,
		author_unit,
		publisher,
		publish_scope,
		publish_time,
		subject_classification,
		category,
		abstract,
		status,
		`/file/essay/${name}.${extName}`,
		remarks,
	]);
	res.send({ status: 200, message: 'upload essay success' });
}

// 修改论文
let essayEditForm;
router.post('/edit', async (req, res) => {
	essayEditForm = req.body.essayEditForm;
	res.send({ status: 100, message: '创建获奖信息成功' });
});
router.post('/edit/upload', upload.single('file'), async (req, res) => {
	file = req.file;
	saveEditFile(file, req, res);
});

async function saveEditFile(file, req, res) {
	let {
		name,
		no,
		keyword,
		author,
		author_unit,
		publisher,
		publish_scope,
		publish_time,
		subject_classification,
		category,
		abstract,
		status,
		remarks,
		essayfile,
	} = essayEditForm;

	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/essay/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let prevFile = path.join(__dirname, `../../public${essayfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `update essay set name= ?,no=? ,author= ? ,keyword= ? ,author_unit= ? ,publisher= ? ,publish_scope= ? ,publish_time= ? ,subject_classification= ? ,category= ? ,abstract= ? ,status= ? ,remarks= ?,essayfile = ? where id = ?`;

	let result = await query(sqlStr, [
		name,
		no,
		author,
		keyword,
		author_unit,
		publisher,
		publish_scope,
		publish_time,
		subject_classification,
		category,
		abstract,
		status,
		remarks,
		`/file/essay/${name}.${extName}`,
		essayEditForm.id,
	]);
	// console.log(result);
	res.send({ status: 200, message: 'success' });
}

// 删除论文
router.delete('/', async (req, res) => {
	let reqQuery = req.query;

	let prevFile = path.join(__dirname, `../../public${reqQuery.essayfile}`);

	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});
	// console.log(query);
	let sqlStr = `delete from essay where id = ?`;
	let result = query(sqlStr, [reqQuery.id]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});
module.exports = router;
